#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
@file_name: reading_data_from_socket.py
@date: 2025-07-29 11:17
@author: Falling Snow
@desc: 从socket中读取数据
"""
import socket

if __name__ == '__main__':
    # 创建socket
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # 绑定端口和地址
    server_address = ("127.0.0.1", 8000)
    server_socket.bind(server_address)
    server_socket.listen()

    try:
        while True:
            # 获取到客户端的数据信息
            connection, client_address = server_socket.accept()
            print(f"来自{client_address}的连接")

            # 设置缓冲区, 存储所有从客户端发送的数据
            buffer = b""
            # 只要最后结尾的字符不是 \r\n 就继续读取数据
            while buffer[-2:] != b"\r\n":
                # 接受2个字节的数据
                data = connection.recv(2)
                # 如果没有数据, 就退出while了
                if not data:
                    break
                else:
                    print(f"我们获取到的客户端数据为: {data}")
                    buffer = buffer + data
            print(f"客户端发送的所有数据为: {buffer[:-2].decode()}")
            connection.sendall(buffer)

    finally:
        server_socket.close()
